package com.kyh.util.wechat;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kyh.util.HttpUtil;

public abstract class WechatWebUtil {
	private static final Logger logger = Logger.getLogger(WechatWebUtil.class);
	private static String appId = "wx32faf1d1087a732f"; // 微信应用ID
	private static String appSecret = "5eae4d48b696a6dc94876ff65338b51d"; // 密钥
	
	public static void getNewAccessToken() {
		
		// 刷新微信凭证
		HttpClient httpClient = new HttpClient();
		
		// 凭证接口地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
				+ "&appid=" + appId
				+ "&secret=" + appSecret;
		// 微信应用ID
		PostMethod postMethod = new PostMethod(requestUrl);
		postMethod.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
		try {
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode == HttpStatus.SC_OK) {
				String resultStr = postMethod.getResponseBodyAsString();
				JSONObject jsonObject = JSON.parseObject(resultStr);
				if (jsonObject.containsKey("access_token")) {
				} else {
				}
			} else {
			}
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getSha1(String str) {
	    if (null == str || 0 == str.length()){
	        return null;
	    }
	    char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
	            'a', 'b', 'c', 'd', 'e', 'f'};
	    try {
	        MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
	        mdTemp.update(str.getBytes("UTF-8"));
	         
	        byte[] md = mdTemp.digest();
	        int j = md.length;
	        char[] buf = new char[j * 2];
	        int k = 0;
	        for (int i = 0; i < j; i++) {
	            byte byte0 = md[i];
	            buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
	            buf[k++] = hexDigits[byte0 & 0xf];
	        }
	        return new String(buf);
	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	        return "";
	    } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
	        return "";
	    }
	}
	
	public static void testSignature() {
		String noncestr = UUID.randomUUID().toString();
		String jsapi_ticket = "kgt8ON7yVITDhtdwci0qef4eBZDsp79H0IA6FKrPjScEsMHoATqfFNjKNj0_13PJCKpGy4ptw6rOyEfjUlyjzQ";
							
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
		String url = "http://127.0.0.1:8020/bgt_html/WEB-INF/jsp/wap/inter/shouye.html";
		
		logger.info("jsapi_ticket=====" + jsapi_ticket);
		logger.info("noncestr=====" + noncestr);
		logger.info("timestamp=====" + timestamp);
		logger.info("url=====" + url);
		
		StringBuffer sb = new StringBuffer();
		sb.append("jsapi_ticket=" + jsapi_ticket)
			.append("&noncestr=" + noncestr)
			.append("&timestamp=" + timestamp)
			.append("&url=" + url);
		String signature = getSha1(sb.toString());
//		String signature = getSha1("jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com?params=value");
		logger.info("signature=====" + signature);
	}
	
	/*
	 * 根据code获取OpenId，用于获取用户信息
	 */
	public static JSONObject getOpenIdByCode(String code) {
		String OAUTHUSERINFO="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		String path = OAUTHUSERINFO.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
		String result = HttpUtil.sendGet(path);
		System.out.println(result);
		JSONObject object=JSONObject.parseObject(result);
//		{"access_token":"f4RPAr3W3RSrwcm_MyRAH32cumyb-fIG3kfC82lQiZxFor0JqhEcVveaPcZwNmNH3m_nvLXDpO0DA3YLWtg9Ar0eln4sC26z3h2hnM9-Wlc","expires_in":7200,"refresh_token":"GcyP1viOKs5A0nLrm2CqthMsb-HFHfHhqpVnpvUU8IygcclrV_CxDdi8lQ-cc5B6BTQxPNuDI84MzAejImc2uWMN7iQ4jSc20zMmalWSTG8","openid":"oWW5Lv9JDq1miGbigKDRHcHtyq9g","scope":"snsapi_userinfo"}
		return object;
	}

	// {"access_token":"9_xZlXW8UT_VnPJCGF6lpsIbr_iDwA4fdIMaLOq_sMVdYbQfh26gR3ocGnq-pf2Q6jo9cuipK5dtqGIrgs5SaWbLTKtgwRMzBYFLMh_0pArjpBKa9c3yMWp4S3wxOJrpXh3wX4U-KZGW-6c7wqIUXbAJACOR","expires_in":7200}
	public static JSONObject getAccessToken() {
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&"
				+ "appid=" + appId
				+ "&secret=" + appSecret;
		String result = HttpUtil.sendGet(requestUrl);
		System.out.println(result);
		JSONObject object = JSONObject.parseObject(result);
		
		return object;
	}

	// {"errcode":0,"errmsg":"ok","ticket":"HoagFKDcsGMVCIY2vOjf9ndOPElNKYWs8g2I24rdaemj3DfqRXHxlWmzcpI9MB4Kuu-wXHjjOO0Hvnu0kjo6hA","expires_in":7200}
	public static JSONObject getShareTicket(String access_token) {
		String OAUTHUSERINFO = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
		String path = OAUTHUSERINFO.replace("ACCESS_TOKEN", access_token);
		String result = HttpUtil.sendGet(path);
		System.out.println(result);
		JSONObject object = JSONObject.parseObject(result);
		
		return object;
	}
	
	/*
	 * 获取用户信息(已授权才可以)
	 * 返回：
		{
			"openid":" OPENID",
			"nickname": NICKNAME,
			"sex":"1",
			"province":"PROVINCE",
			"city":"CITY",
			"country":"COUNTRY",
			"headimgurl":"http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
			"privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
			"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
		}
	 */
	public static JSONObject getUserInfoByOpenidAndToken(String openid, String access_token) {
		String OAUTHUSERINFO="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
		String path = OAUTHUSERINFO.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
		String result = HttpUtil.sendGet(path);
		System.out.println(result);
		JSONObject object=JSONObject.parseObject(result);
//		{"openid":"oWW5Lv9JDq1miGbigKDRHcHtyq9g","nickname":"Jason谢德海","sex":1,"language":"zh_CN","city":"莆田","province":"福建","country":"中国","headimgurl":"http:\/\/wx.qlogo.cn\/mmhead\/ZMdxSDafpxQ3wuYKLo4eYCoyknRLlmUwubrUUEerZmgvuOMciaAm6gw\/0","privilege":[]}
//		{"errcode":40001,"errmsg":"invalid credential, access_token is invalid or not latest, hints: [ req_id: qJ8XGa0510s184 ]"}
		return object;
	}
	
	/*
	 * 获取用户信息(已关注后才可以)
	 * 参数：access_token：非临时的
	 * 返回：
		{
			"subscribe":0,
			"openid":"oWW5Lv9JDq1miGbigKDRHcHtyq9g",
			"tagid_list":[]
		}
	 */
	public static JSONObject getUserInfo(String access_token, String openid) {
//		String openid = "oWW5Lv9JDq1miGbigKDRHcHtyq9g";
		String OAUTHUSERINFO="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
		String path = OAUTHUSERINFO.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
		String result = HttpUtil.sendGet(path);
		System.out.println(result);
		// {"subscribe":0,"openid":"oWW5Lv9JDq1miGbigKDRHcHtyq9g","tagid_list":[]}
		// {"subscribe":1,"openid":"oWW5Lv9JDq1miGbigKDRHcHtyq9g","nickname":"Jason谢德海","sex":1,"language":"zh_CN","city":"莆田","province":"福建","country":"中国","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/lHGIrkia7gicOnVsQWz78thSvEyonA99dFOAaWwhZIDqH2a08iaY5cf0ZtcTdBHWPdZka8H03PRw50L97v4l0Qp3IDnBGwibGO3E\/0","subscribe_time":1500216732,"remark":"","groupid":0,"tagid_list":[]}
		JSONObject object=JSONObject.parseObject(result);
		return object;
	}
	
	public static void main(String[] args) {

		JSONObject JOAccessToken = WechatWebUtil.getAccessToken();
		String access_token = JOAccessToken.getString("access_token");
		
		JSONObject JOTicket = WechatWebUtil.getShareTicket(access_token);
		String ticket = JOTicket.getString("ticket");
		System.out.println(ticket);
		
	}
}
